IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RepopulateDefaultConstraints'))
BEGIN
	DROP PROCEDURE MD3.RepopulateDefaultConstraints
END
GO

CREATE Procedure MD3.RepopulateDefaultConstraints

AS  
BEGIN

/*
	Blows away all entries in MD3.CheckConstraints table, EXCEPT entries with DropConstraint.  We need to maintain this "state"
	Repopulates the table with current constraint information from the current database


*/

SET NOCOUNT ON  

	DELETE FROM MD3.DefaultConstraints WHERE DropConstraint = 0
	

    SET NOCOUNT ON  
	INSERT INTO MD3.DefaultConstraints
		(TableName,SchemaName,ConstraintName,ConstraintExpression,ColumnName,DropConstraint)
	SELECT 
		Const.TableName,Const.SchemaName,Const.ConstraintName,Const.ConstraintExpression,Const.ColumnName, 0
	FROM sys.objects AS o
	JOIN sys.schemas AS s 
		ON o.schema_id = s.schema_id
	CROSS APPLY MD3.f_GetConstraints(s.Name, o.Name) as Const
	WHERE o.type = 'U'
	AND s.name <> 'MD3'
	AND Const.ConstraintType = 'DEFAULT'
	ORDER BY 
		SCHEMA_NAME(o.schema_id),
		o.Name


	
END
GO
